package com.xbongbong.parent.abstracts;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.BusinessLinkProductService;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.model.ProductModel;
import org.apache.commons.collections4.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2022/05/24 9:59
 */
public abstract class AbstractBusinessLinkProductService implements BusinessLinkProductService {

    @Resource
    private ProductModel productModel;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;

    /**
     * 将关联产品set到各个业务的attr中
     * @param corpid 公司id
     * @param paasFormDataESList 数据
     * @param linkProductList 关联产品的产品字段
     * @param productIdSet 产品id
     * @param productDataMap  以机会id为key，关联产品为value的数据集合
     * @param attr 各个业务的关联产品的attr
     * @throws XbbException
     */
    public void setLinkProduct(String corpid, List<PaasFormDataEntityExt> paasFormDataESList, List<FieldAttrEntity> linkProductList, Set<Long> productIdSet, Map<Long, List<JSONObject>> productDataMap, String attr) throws XbbException {

        Map<Long, PaasFormDataEntityExt> productMap = productModel.getProductSpecificationMap(productIdSet, corpid);

        Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        // TODO  此处可优化时间复杂度
        for (PaasFormDataEntityExt entity : paasFormDataESList) {
            List<JSONObject> dataList = productDataMap.get(entity.getDataId());
            if (CollectionUtils.isEmpty(dataList)) {
                continue;
            }
            dataList.forEach(jsonObject->{
                if (productMap.containsKey(jsonObject.getLong(StringConstant.DATA_ID))){
                    PaasFormDataEntityExt product = productMap.get(jsonObject.getLong(StringConstant.DATA_ID));
                    for (FieldAttrEntity item : linkProductList){
                        if (Objects.equals(item.getFieldType(), FieldTypeEnum.SERIALNO.getType())){
                            jsonObject.put(item.getAttr(), product.getSerialNo());
                        }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.ADDTIME.getType())){
                            jsonObject.put(item.getAttr(), product.getAddTime());
                        }else if (Objects.equals(item.getFieldType(),FieldTypeEnum.UPDATETIME.getType())){
                            jsonObject.put(item.getAttr(), product.getUpdateTime());
                        }else {
                            jsonObject.put(item.getAttr(), product.getData().get(item.getSaasAttr()));
                        }
                    }
                    // 多单位
                    JSONObject productData = product.getData();
                    if (BasicConstant.ONE.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                        String businessUnitVal = jsonObject.getString(SelectProductEnum.UNIT.getAttr());
                        long unitGroupId = productData.getLongValue(ProductEnum.UNIT.getAttr());
                        List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(unitGroupId);
                        jsonObject.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                        if (!StringUtil.isDigital(businessUnitVal) || Long.parseLong(businessUnitVal) < ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                            MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.getOrDefault(unitGroupId, new MultiUnitItemPoJo());
                            jsonObject.put(SelectProductEnum.UNIT.getAttr(), multiUnitItemPoJo.getBaseValue());
                        }
                    }
                }
            });
            entity.getData().put(attr, dataList);
        }
    }

    /**
     * 获取产品名称可见权限
     * 抽离于-》com.xbongbong.saas.help.SaasListHelp#analysisListProductData(java.util.List, java.util.List, java.lang.Integer, java.lang.String, java.lang.Integer, java.lang.Integer, com.xbongbong.paas.pojo.dto.FormDataListDTO)第3485行
     * @param userVO
     * @param corpid
     * @return
     * @throws XbbException
     */
    protected boolean getProductNameVisible(UserVO userVO, String corpid) throws XbbException {
        PaasFormExplainEntity productExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (Objects.nonNull(productExplain)) {
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByAttr(productExplain.getExplains(), ProductEnum.NAME.getAttr());
            FieldAttrEntity fieldAttrEntity = explainMap.get(ProductEnum.NAME.getAttr());
            if (Objects.equals(fieldAttrEntity.getVisibleScopeEnable(), 1)) {
                VisibleRulePoJo visibleScopeRule = fieldAttrEntity.getVisibleScopeRule();
                if (Objects.nonNull(visibleScopeRule)) {
                    fieldAttrEntity.getVisibleScopeRule().setRelative(new ArrayList<>());
                    HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                    handlerExplainDTO.setLoginUser(userVO);
                    handlerExplainDTO.setUserId(userVO.getUserId());
                    // 此处无法判断高级权限校验，因为没有负责人和协同人，创建人，只能判断角色，部门，人员是否可见
                    return ExplainUtil.isFieldNeedHide(fieldAttrEntity, handlerExplainDTO);
                }
            }
        }
        return false;
    }

}
